package com.tingyukeji.fastpay.sport.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.PolylineOptions;
import com.tingyukeji.fastpay.R;
import com.tingyukeji.fastpay.base.BaseActivity;
import com.tingyukeji.fastpay.databinding.RunRecordActivityBinding;
import com.tingyukeji.fastpay.sport.adapter.DbAdapter;
import com.tingyukeji.fastpay.sport.model.PathRecord;
import com.tingyukeji.fastpay.utils.MapUtils;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RunRecordActivity extends BaseActivity implements OnMapLoadedListener {
	private final static int AMAP_LOADED = 2;
	private AMap mAMap;
	private int mRecordItemId;
	private List<LatLng> mOriginLatLngList;
	private ExecutorService mThreadPool;
	private RunRecordActivityBinding binding;
	private PathRecord mPathRecord = new PathRecord();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		binding = DataBindingUtil.setContentView(this, R.layout.run_record_activity);
		binding.map.onCreate(savedInstanceState);// 此方法必须重写
		Intent recordIntent = getIntent();
		int threadPoolSize = Runtime.getRuntime().availableProcessors() * 2 + 3;
		mThreadPool = Executors.newFixedThreadPool(threadPoolSize);
		if (recordIntent != null) {
			mRecordItemId = recordIntent.getIntExtra(RecordActivity.RECORD_ID,-1);
		}
		Bundle bundle = getIntent().getExtras();
		if (null != bundle){
			mPathRecord.setDistance(String.valueOf(bundle.getFloat("distance")));
			mPathRecord.setDuration(bundle.getString("duration"));
			mPathRecord.setDate(bundle.getString("time"));
			mPathRecord.setPathline(bundle.<AMapLocation>getParcelableArrayList("list"));
			mPathRecord.setStartpoint((AMapLocation) bundle.getParcelable("firstLocaiton"));
			mPathRecord.setEndpoint((AMapLocation) bundle.getParcelable("lastLocaiton"));
		}
		initMap();
	}

	private void initMap() {
		if (mAMap == null) {
			mAMap = binding.map.getMap();
			mAMap.setOnMapLoadedListener(this);
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case AMAP_LOADED:
				setupRecord();
				break;
			default:
				break;
			}
		}

	};

	public void onBackClick(View view) {
		this.finish();
		if (mThreadPool != null) {
			mThreadPool.shutdownNow();
		}
	}

	public void onDestroy() {
		super.onDestroy();
		if (mThreadPool != null) {
			mThreadPool.shutdownNow();
		}
	}

	private LatLngBounds getBounds() {
		LatLngBounds.Builder b = LatLngBounds.builder();
		if (mOriginLatLngList == null) {
			return b.build();
		}
		for (int i = 0; i < mOriginLatLngList.size(); i++) {
			b.include(mOriginLatLngList.get(i));
		}
		return b.build();

	}

	/**
	 * 轨迹数据初始化
	 * 
	 */
	private void setupRecord() {
		if (null == mPathRecord){
			DbAdapter dbhelper = new DbAdapter(this.getApplicationContext());
			dbhelper.open();
			mPathRecord = dbhelper.queryRecordById(mRecordItemId);
			dbhelper.close();
		}
		if (mPathRecord != null) {
			List<AMapLocation> recordList = mPathRecord.getPathline();
			AMapLocation startLoc = mPathRecord.getStartpoint();
			AMapLocation endLoc = mPathRecord.getEndpoint();
			if (recordList == null || startLoc == null || endLoc == null) {
				return;
			}
			mOriginLatLngList = MapUtils.parseLatLngList(recordList);
			addOriginTrace(mOriginLatLngList);
		}
	}

	/**
	 * 地图上添加原始轨迹线路
	 * 
	 * @param originList
	 */
	private void addOriginTrace(List<LatLng> originList) {
		mAMap.addPolyline(new PolylineOptions().color(
				Color.BLUE).addAll(originList));
		try {
			mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(),50));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onMapLoaded() {
		Message msg = handler.obtainMessage();
		msg.what = AMAP_LOADED;
		handler.sendMessage(msg);
	}
}
